import 'package:flutter/foundation.dart';
import '../services/database_helper.dart';
import '../models/bill.dart';
import '../models/bill_item.dart';


class BillProvider with ChangeNotifier {
  List<Bill> _bills = [];
  List<Bill> get bills => _bills;

  bool _isLoading = false;
  bool get isLoading => _isLoading;

  
  String? _currentFilter;
   // 添加公共访问器
  String? get currentFilter => _currentFilter; // 添加这行

  // ----------------------------------------------------------------------- 阶段3目标：时间分组折叠列表
   // 添加分组数据结构
  Map<String, Map<String, List<Bill>>> _groupedBills = {};
  Map<String, bool> _expansionStates = {};

    // 获取分组后的账单
  Map<String, Map<String, List<Bill>>> get groupedBills => _groupedBills;
  Map<String, bool> get expansionStates => _expansionStates;

  // 分组方法
  void _groupBillsByDate() {
    _groupedBills.clear();
    _expansionStates.clear();

    for (var bill in _bills) {
      final yearMonth = bill.yearMonth; // 例如: "2024-01"
      final fullDate = bill.fullDate;   // 例如: "2024-01-15"

      if (!_groupedBills.containsKey(yearMonth)) {
        _groupedBills[yearMonth] = {};
      }
      if (!_groupedBills[yearMonth]!.containsKey(fullDate)) {
        _groupedBills[yearMonth]![fullDate] = [];
      }

      _groupedBills[yearMonth]![fullDate]!.add(bill);
      
      // 初始化展开状态（默认折叠）
      if (!_expansionStates.containsKey(yearMonth)) {
        _expansionStates[yearMonth] = false;
      }
    }
  }

  // 切换分组展开状态
  void toggleExpansion(String key) {
    if (_expansionStates.containsKey(key)) {
      _expansionStates[key] = !_expansionStates[key]!;
      notifyListeners();
    }
  }



 // ----------------------------------------------------------------------- 阶段3目标：时间分组折叠列表







  // 加载所有账单
  Future<void> loadBills({String? status}) async {
    _isLoading = true;
    notifyListeners();


    

    try {
      final db = DatabaseHelper();
      _bills = await db.getBills(status: status); // 确保这里使用了 db
      _currentFilter = status;
      // 分组账单
      _groupBillsByDate();
    } catch (e) {
      print('加载账单失败: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 在 BillProvider 类中更新 createBill 方法
  Future<int> createBill(Bill bill, List<BillItem> billItems) async {
    try {
      final db = DatabaseHelper();
      
      // 使用支持价格保护的事务方法
      final billId = await db.createBillWithPriceProtection(bill, billItems);

      // 重新加载账单列表
      await loadBills(status: _currentFilter);
      return billId;
    } catch (e) {
      print('创建账单失败: $e');
      rethrow;
    }
  }

  // 更新账单状态
  Future<void> updateBillStatus(int billId, String status) async {
    try {
      final db = DatabaseHelper();
      await db.updateBillStatus(billId, status);

      // 更新本地状态
      final index = _bills.indexWhere((bill) => bill.id == billId);
      if (index != -1) {
        _bills[index] = _bills[index].copyWith(status: status);
        notifyListeners();
      }
    } catch (e) {
      print('更新账单状态失败: $e');
      rethrow;
    }
  }

  // 获取账单的账单项
  Future<List<BillItem>> getBillItems(int billId) async {
    try {
      return await DatabaseHelper().getBillItemsByBillId(billId);
    } catch (e) {
      print('获取账单项失败: $e');
      rethrow;
    }
  }

  // 删除账单
  Future<void> deleteBill(int billId) async {
    try {
      final db = DatabaseHelper();
      await db.deleteBill(billId);

      // 从本地列表中移除
      _bills.removeWhere((bill) => bill.id == billId);
      notifyListeners();
    } catch (e) {
      print('删除账单失败: $e');
      rethrow;
    }
  }

  // 根据ID获取账单
  Future<Bill?> getBillById(int id) async {
    try {
      return await DatabaseHelper().getBillById(id);
    } catch (e) {
      print('获取账单详情失败: $e');
      return null;
    }
  }

    // 添加账单项到现有账单
  Future<int> addBillItem(BillItem billItem) async {
    try {
      final db = DatabaseHelper();
      final result = await db.insertBillItem(billItem);
      
      // 重新加载账单列表以更新总金额
      await loadBills(status: _currentFilter);
      return result;
    } catch (e) {
      print('添加账单项失败: $e');
      rethrow;
    }
  }

  // 添加修改历史记录
  Future<void> addModificationHistory(int billId, BillModification modification) async {
    try {
      final db = DatabaseHelper();
      // 首先获取当前账单
      final bill = await db.getBillById(billId);
      if (bill != null) {
        // 更新修改历史
        final updatedHistory = List<BillModification>.from(bill.modificationHistory)..add(modification);
        final updatedBill = bill.copyWith(modificationHistory: updatedHistory);
        
        // 更新账单
        await db.updateBill(updatedBill);
      }
    } catch (e) {
      print('添加修改历史失败: $e');
      rethrow;
    }
  }

  // 获取账单修改历史
  Future<List<BillModification>> getBillModificationHistory(int billId) async {
    try {
      final db = DatabaseHelper();
      final bill = await db.getBillById(billId);
      return bill?.modificationHistory ?? [];
    } catch (e) {
      print('获取修改历史失败: $e');
      return [];
    }
  }

  // 获取统计信息
  Future<Map<String, dynamic>> getStatistics(DateTime startDate, DateTime endDate) async {
    try {
      return await DatabaseHelper().getBillStatistics(startDate, endDate);
    } catch (e) {
      print('获取统计信息失败: $e');
      return {};
    }
  }

  // 在 BillProvider 类中添加以下方法
Future<int> updateBill(Bill bill) async {
  final dbHelper = DatabaseHelper();
  final db = await dbHelper.database;
  final now = DateTime.now().millisecondsSinceEpoch;
  
  final Map<String, dynamic> billMap = bill.toMap();
  billMap['updated_at'] = now;
  
  return await db.update(
    'bills',
    billMap,
    where: 'id = ?',
    whereArgs: [bill.id],
  );
}
// 更新账单项
Future<int> updateBillItem(BillItem billItem) async {
  try {
    final db = DatabaseHelper();
    final result = await db.updateBillItem(billItem);
    
    // 重新加载账单列表以更新总金额
    await loadBills(status: _currentFilter);
    return result;
  } catch (e) {
    print('更新账单项失败: $e');
    rethrow;
  }
}

// 重新计算账单总金额
Future<double> recalculateBillTotal(int billId) async {
  try {
    final billItems = await getBillItems(billId);
    double newTotal = 0.0;
    
    for (var item in billItems) {
      newTotal += item.subtotal;
    }
    
    return newTotal;
  } catch (e) {
    print('重新计算总金额失败: $e');
    rethrow;
  }
}

Future<int> deleteBillItem(int billItemId) async {
  try {
    final db = DatabaseHelper();
    final result = await db.deleteBillItem(billItemId);
    
    // 重新加载账单列表以更新总金额
    await loadBills(status: _currentFilter);
    return result;
  } catch (e) {
    print('删除账单项失败: $e');
    rethrow;
  }
}

  // 添加获取价格快照的方法
  Future<double?> getPriceSnapshot(int billId, int productId) async {
    try {
      final db = DatabaseHelper();
      return await db.getPriceSnapshot(billId, productId);
    } catch (e) {
      print('获取价格快照失败: $e');
      return null;
    }
  }






  // 清除账单数据
  void clearBills() {
    _bills.clear();
    notifyListeners();
  }
}